//
//  MSCollectDetailView.m
//  MSJD
//
//  Created by 箭军刘 on 2018/10/19.
//  Copyright © 2018年 xiangbo. All rights reserved.
//

#import "MSCollectDetailView.h"

#import "MSHotelCell.h"
#import "MSEmptyView.h"
#import "MSCollectStoreCell.h"

#import "MSCollectDataSource.h"
#import "MSSearchDataSource.h"

@interface MSCollectDetailView()
<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, copy) NSArray *collectList;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, strong) MSEmptyView *emptyView;

@property (nonatomic, assign) MSCollectDetailViewType type;
@property (nonatomic, copy) NSDictionary *filterParam; // 筛选页的参数

@property (nonatomic, assign) BOOL isFristLoad;

@end

@implementation MSCollectDetailView

- (instancetype)initWithFrame:(CGRect)frame type:(MSCollectDetailViewType)type {
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor clearColor];
        
        self.type = type;
        
        [self initSubViews];
        
        self.page = 1;
        self.pageSize = 10;
        
        if (type != MSCollectDetailViewTypeFavoriteStore) {
            // 店铺详情界面刚进去时不自动刷新，等以后展示时调用
            self.isFristLoad = NO;
            [self.tableView.mj_header beginRefreshing];
        } else {
            self.isFristLoad = YES;
        }
    }
    return self;
}

#pragma mark - Init Method

- (void)initSubViews {
    [self addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
}
/** 加载收藏列表数据 */
- (void)loadCollectListData {
    
    if (self.type == MSCollectDetailViewTypeFilter) {
        // 筛选页
        NSDictionary *param = [MSSafeObject dictionaryInfo:self.filterParam];
        _WEAKSELF
        [MSSearchDataSource searchContentListWithFilterParam:param page:self.page size:self.pageSize success:^(NSDictionary * _Nonnull responseInfo) {
            [weakSelf stopMJRefresh];
            [weakSelf loadCollectListSuccess:responseInfo];
        } failure:^(NSError * _Nonnull error) {
            [weakSelf stopMJRefresh];
            NSString *errorMsg = error.localizedDescription?:@"查询筛选数据失败";
            [weakSelf queryListFailure:errorMsg];
        }];
        return;
    }
    // 收藏
    if (self.emptyView) {
        [self.emptyView removeFromSuperview];
        self.emptyView = nil;
    }
    // 收藏页
    _WEAKSELF
    NSInteger kind = (self.type == MSCollectDetailViewTypeFavoriteHotel)?2:1;
    [MSCollectDataSource queryCollectDataWithKind:kind page:self.page pageSize:self.pageSize success:^(NSDictionary * _Nonnull responseInfo) {
        [weakSelf stopMJRefresh];
        [weakSelf loadCollectListSuccess:responseInfo];
    } failure:^(NSError * _Nonnull error) {
        [weakSelf stopMJRefresh];
        NSString *errorMsg = error.localizedDescription?:@"查询收藏数据失败";
        [weakSelf queryListFailure:errorMsg];
    }];
}
/** 获取收藏数据成功 */
- (void)loadCollectListSuccess:(NSDictionary *)response {
    if ([MSSafeObject isNull:response]) {
        return;
    }
    NSArray *array = [MSSafeObject ArrayInfo:response[@"rows"]];
    
    if (self.page == 1) {
        // 头部刷新
        self.collectList = array;
        [self.tableView reloadData];
        if (self.collectList.count < 1) {
            NSString *emptyMsg = @"";
            switch (self.type) {
                case MSCollectDetailViewTypeFavoriteHotel:
                    emptyMsg = @"您还没有收藏的酒店";
                    break;
                case MSCollectDetailViewTypeFavoriteStore:
                    emptyMsg =@"您还没有收藏的店铺";
                    break;
                default:
                    emptyMsg = @"没有查询到合适的数据";
                    break;
            }
            [self showEmptyViewWithType:0 message:emptyMsg];
            return;
        }
    } else {
        // 加载更多
        NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.collectList];
        [tempArr addObjectsFromArray:array];
        self.collectList = tempArr.copy;
        [self.tableView reloadData];
    }
    // footer的状态
    self.tableView.mj_footer.hidden = NO;
    NSInteger totalPage = [response[@"totalPage"] integerValue];
    NSInteger page = [response[@"page"] integerValue];
    if (totalPage <= page) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        self.page ++;
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.collectList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.type == MSCollectDetailViewTypeFavoriteStore) {
        MSCollectStoreCell *storeCell = [tableView dequeueReusableCellWithIdentifier:@"MSCollectStoreCell"];
        if (indexPath.row < self.collectList.count) {
            NSDictionary *collectDic = self.collectList[indexPath.row];
            MSFoodDetailData *foodDetail = [MSFoodDetailData modelWithJSON:collectDic];
            [storeCell refreshCollectStoreCellWithModel:foodDetail];
        }
        return storeCell;
    }
    MSHotelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MSHotelCell"];
    if (indexPath.row < self.collectList.count) {
        NSDictionary *collectDic = self.collectList[indexPath.row];
        MSFoodDetailData *detailData = [MSFoodDetailData modelWithJSON:collectDic];
        [cell refreshHotelCellWithData:detailData isFilter:YES];
    }
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.type == MSCollectDetailViewTypeFavoriteStore) {
        return 227.0;
    }
    return 137.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (labs(indexPath.row) < self.collectList.count) {
        NSDictionary *collectDic = self.collectList[indexPath.row];
        MSFoodDetailData *detailData = [MSFoodDetailData modelWithJSON:collectDic];
        [MSJumpConn jumpToMSDetailViewController:detailData];
    }
}

// 是否允许侧滑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.type == MSCollectDetailViewTypeFavoriteHotel ||
        self.type == MSCollectDetailViewTypeFavoriteStore) {
        return YES;
    }
    return NO;
}

// 侧滑按钮
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
//    UITableViewRowAction *shareRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"分享" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        // 点击分享按钮
//        [self didSelectCollectViewSideButtonWithType:0 row:indexPath.row];
//    }];
//    shareRowAction.backgroundColor = [UIColor colorWithHexString:@"#717171"];
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        // 点击了删除按钮
        [self didSelectCollectViewSideButtonWithType:1 row:indexPath.row];
    }];
    deleteRowAction.backgroundColor = [UIColor colorWithHexString:@"#EF4640"];
//    return @[deleteRowAction, shareRowAction];
    return @[deleteRowAction];
}

#pragma mark - Event Response
/** 头部刷新 */
- (void)collectHeaderRefresh {
    [self removeEmptyView];
    self.page = 1;
    [self loadCollectListData];
}
/** 底部刷新 */
- (void)collectFooterRefresh {
    [self loadCollectListData];
}

#pragma mark - Public Method

- (void)firstShow {
    if (!self.isFristLoad) {
        return;
    }
    if (self.type == MSCollectDetailViewTypeFavoriteStore) {
        // 店铺刷新界面才会调用这个
        self.isFristLoad = NO;
        [self.tableView.mj_header beginRefreshing];
    }
}

- (void)refreshTabelViewWithNewParam:(NSDictionary *)param filterDic:(nonnull NSDictionary *)filterDic {
    NSMutableDictionary *tempFilterParam = [NSMutableDictionary dictionaryWithDictionary:param];
    [tempFilterParam addEntriesFromDictionary:filterDic];
    self.filterParam = tempFilterParam.copy;
    [self.tableView.mj_header beginRefreshing];
}

- (void)refreshCollectList {
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - Private Method

/** 点击收藏cell的侧滑按钮 type:按钮类型(0:分享1:删除) row:cell的行号 */
- (void)didSelectCollectViewSideButtonWithType:(NSInteger)type row:(NSInteger)row {
    [self.tableView setEditing:NO animated:YES];
    if (type == 0) {
        // 分享
        
    } else {
        // 删除
        if (self.collectList.count <= row) {
            return;
        }
        [self removeHotelCollectWithRow:row];
    }
}
/** 移除对某个酒店的收藏 */
- (void)removeHotelCollectWithRow:(NSInteger)row {
    _WEAKSELF
    [MBProgressHUD showMessage:@""];
    NSDictionary *hotelInfo = self.collectList[row];
    NSInteger hotelId = [hotelInfo[@"id"] integerValue];
    [MSCollectDataSource removeCollectDataWithHotelId:hotelId success:^(NSDictionary * _Nonnull responseInfo) {
        [MBProgressHUD hideHUD];
        [weakSelf removeHotelSuccessWithRow:row];
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        NSString *errorMsg = error.localizedDescription?:@"取消收藏失败";
        [MBProgressHUD showDefaultHUDWithText:errorMsg toView:weakSelf];
    }];
}
/** 移除收藏的酒店成功 */
- (void)removeHotelSuccessWithRow:(NSInteger)row {
    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.collectList];
    [tempArr removeObjectAtIndex:row];
    self.collectList = tempArr.copy;
    if (self.collectList.count < 1) {
        [self showEmptyViewWithType:0 message:@"您还没有收藏的酒店"];
        [self.tableView reloadData];
    } else {
        [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }
}

/** 查询数据失败 */
- (void)queryListFailure:(NSString *)errorMsg {
    [self stopMJRefresh];
    
    [MBProgressHUD showToastWithMessage:errorMsg toView:self];
    if (self.collectList.count < 1) {
        [self showEmptyViewWithType:1 message:@"页面刷新失败"];
    }
}
/** 停止MJ刷新 */
- (void)stopMJRefresh {
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }
}
/** 展示空提示界面 */
- (void)showEmptyViewWithType:(NSInteger)type message:(NSString *)message {
    MSEmptyView *emptyView = [MSEmptyView loadEmptyViewWithType:type toast:message frame:CGRectMake(0, -40, MS_SCREEN_WIDTH, MS_SCREEN_HEIGHT)];
    // 重试按钮点击
    _WEAKSELF
    emptyView.RetryButtonClickBlock = ^{
        [weakSelf loadCollectListData];
    };
    [self addSubview:emptyView];
    self.emptyView = emptyView;
}

- (void)removeEmptyView {
    if (self.emptyView) {
        [self.emptyView removeFromSuperview];
        self.emptyView = nil;
    }
}

#pragma mark - Getters

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = 113.0f;
        
        // 注册普通列表cell
        if (self.type == MSCollectDetailViewTypeFavoriteStore) {
            [_tableView registerNib:[UINib nibWithNibName:@"MSCollectStoreCell" bundle:nil] forCellReuseIdentifier:@"MSCollectStoreCell"];
        } else {
            [_tableView registerNib:[UINib nibWithNibName:@"MSHotelCell" bundle:nil] forCellReuseIdentifier:@"MSHotelCell"];
        }

        // 添加刷新控件
        MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(collectFooterRefresh)];
        footer.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
        footer.hidden = YES;
        _tableView.mj_footer = footer;
        
        MJRefreshStateHeader *header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(collectHeaderRefresh)];
        header.stateLabel.textColor = MSThemeColor;
        header.lastUpdatedTimeLabel.alpha = 1.0;
        _tableView.mj_header = header;
    }
    return _tableView;
}


@end
